package com.doge.walknovel.business.home.profile.topup

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.doge.walknovel.api.model.RechargeProductInfo
import com.doge.walknovel.core.base.adapters.BaseAdapter

class TopUpAdapter : BaseAdapter() {
    private val dataList = mutableListOf<RechargeProductInfo>()
    private var lastSelected: RechargeProductInfo? = null
    val selected: RechargeProductInfo? get() = lastSelected

    fun set(data: List<RechargeProductInfo>) {
        dataList.clear()
        dataList.addAll(data)
        notifyDataSetChanged()
        select()
    }

    fun select(data: RechargeProductInfo? = null) {
        val selected = data ?: lastSelected ?: dataList.firstOrNull()
        dataList.forEach {
            it.appSelected = it.rechargeId == selected?.rechargeId
        }
        lastSelected = selected
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int = dataList.size
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return TopUpViewHolder(parent, callback)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val item = if (position < dataList.size) dataList[position] else null
        when (holder) {
            is TopUpViewHolder -> item?.let { holder.bind(it) }
        }
    }
}

